﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using PortalCurriculo.Domain;
using PortalCurriculo.MvcWebUI.Models;

namespace PortalCurriculo.MvcWebUI.Controllers
{
    public class AccountController : ControllerBase
    {
        const string MatchEmailPattern =
            @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
             + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
             + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
             + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        public string Erro { get; set; }

        private bool ValidateLogOn(string email, string password)
        {
            if (String.IsNullOrEmpty(email))
            {
                Erro = Resources.Account.Logon.EmailInvalido;
                return false;
            }
            if (String.IsNullOrEmpty(password))
            {
                Erro = Resources.Account.Logon.SenhaInvalida;
                return false;
            }
            if (!System.Text.RegularExpressions.Regex.IsMatch(email, MatchEmailPattern))
            {
                Erro = Resources.Account.Logon.EmailInvalido;
                return false;
            }

            return true;
        }

        private ActionResult AutenticarUsuario(string email, string senha, string returnUrl)
        {
            ClearAllSessions();

            var usuario = new Usuario
                              {
                                  Senha = senha,
                                  Pessoa = new Pessoa { Email = email }
                              };

            usuario = usuario.Autenticar();

            if (usuario != null)
            {
                //var selecionadorEmpresas = new SelecionadorEmpresa().AutenticarSelecionador(usuario);

                //if (selecionadorEmpresas.Count > 0)
                //{
                //    usuario = selecionadorEmpresas.First().Selecionador.Usuario;
                //    WebSession(SessionName.SelecionadorLogado, selecionadorEmpresas.First().Selecionador);

                //    var empresas = selecionadorEmpresas.Select(selecionadorEmpresa => selecionadorEmpresa.Empresa1).ToList();
                //    WebSession(SessionName.EmpresasSelecionadorLogado, empresas);
                //}
            }

            if (usuario == null)
            {
                Erro = Resources.Account.Logon.EmailNaoCadastrado;
                return View();
            }


            if (usuario.SenhaInvalida)
            {
                Erro = Resources.Account.Logon.SenhaInvalida;
                return View();
            }

            if (usuario.LoginAtivo == false)
            {
                Erro = Resources.Account.Logon.LoginNaoAtivo;
                return View();
            }

            if (usuario.Pessoa == null) usuario.Pessoa = new Pessoa().SelectById<Pessoa>(usuario.IdPessoa);

            PreencherSessoes(usuario);

            Nome = usuario.Pessoa.PessoaFisica != null
                              ? usuario.Pessoa.PessoaFisica.NomeCompleto
                              : usuario.Pessoa.PessoaJuridica.NomeFantasia;

            FormsAuthentication.SetAuthCookie(Nome.Split(' ').First(), false);
            //FormsAuthentication.SetAuthCookie("dtrdtr", false);

            //var returnUrl = Request.QueryString.Get("returnurl");

            return Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                       && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")
                           ? (ActionResult)Redirect(returnUrl)
                           : RedirectToAction("Index", "Home");
        }

        private void PreencherSessoes(Usuario usuario)
        {
            if (usuario.Pessoa.PessoaFisica != null)
            {
                if (WebSession(SessionName.SelecionadorLogado) == null)
                {
                    WebSession(SessionName.AdministradorLogado,
                               new Administrador { IdUsuario = usuario.Id }.Selecionar());
                    WebSession(SessionName.ProfissionalLogado,
                               new Profissional { IdUsuario = usuario.Id }.Selecionar());
                    WebSession(SessionName.RedatorLogado,
                               new Redator { IdUsuario = usuario.Id }.Selecionar());
                }
            }
            else
            {
                WebSession(SessionName.EmpresaLogada,
                           new Empresa { IdUsuario = usuario.Id }.Selecionar());
            }

            WebSession(SessionName.ParceiroLogado, new Parceiro { IdUsuario = usuario.Id }.Selecionar());
            WebSession(SessionName.UsuarioLogado, usuario);
        }


        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            return ValidateLogOn(model.UserName, model.Password)
                       ? AutenticarUsuario(model.UserName, model.Password, model.ReturnUrl)
                       : View();
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOnPartial()
        {
            return PartialView();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOnPartial(LogOnModel model, string returnUrl)
        {
            if (Request.IsAjaxRequest())
            {
                if (ValidateLogOn(model.UserName, model.Password))
                    AutenticarUsuario(model.UserName, model.Password, model.ReturnUrl);

                return !string.IsNullOrEmpty(Erro)
                           ? Json(new {logged = false, mensagem = Erro})
                           : Json(new { logged = true, usuario = Nome.Split(' ').First()});
            }

            return PartialView();
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return PartialView();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        public string Nome { get; set; }
    }
}
